package main

import (
	"bytes"
	"encoding/json"
	"fmt"
	"net/http"

	logger "github.com/sirupsen/logrus"
)

type Dinghook struct {
	name       string         //机器人的名字(消息的抬头)
	url        string         //机器人的token
	levels     []logger.Level //
	toMobiles  []string       //目标手机号
	jsonBodies chan []byte    //异步发送内容队列
	chan_Close chan bool      //主进程关闭消息通道
}

//Levels 代表在哪几个级别下应用这个hook
func (dh *Dinghook) Levels() []logger.Level {
	return dh.levels
}

//Fire  代表执行哪些逻辑
func (dh *Dinghook) Fire(e *logger.Entry) error {
	msg,_:= e.String()
	dh.DirectSend(msg)
	return nil
}

//同步发送钉钉的函数
func (dh *Dinghook) DirectSend(msg string) {
	dm := dingMsg{
		MsgType: "text",
	}
	dm.Text.Content = fmt.Sprintf("[外星人入侵]\n[app=%s]\n"+
		"[日志详情：%s]", dh.name, msg)
	dm.At.AtMobiles = dh.toMobiles
	bs, err := json.Marshal(dm)
	if err != nil {
		logger.Errorf("[消息json.marshal失败][error:%v][msg:%v]", err, msg)
		return
	}
	res, err := http.Post(dh.url, "application/json", bytes.NewBuffer(bs))
	if err != nil {
		logger.Errorf("[消息发送失败][error:%v][msg:%v]",err,msg)
		return
	}
	if res != nil && res.StatusCode != 200 {
		logger.Errorf("[钉钉返回错误][StatusCode:%v][msg:%v]",res.StatusCode,msg)
		return
	}

}

/*
{
    "at": {
        "atMobiles":[
            "180xxxxxx"
        ],
        "atUserIds":[
            "user123"
        ],
        "isAtAll": false
    },
    "text": {
        "content":"我就是我, @XXX 是不一样的烟火"
    },
    "msgtype":"text"
}
*/
type dingMsg struct {
	MsgType string `json:"msgtype"`
	Text    struct {
		Content string `json:"content"`
	} `json:"text"`
	At struct {
		AtMobiles []string `json:"atMobiles"`
	} `json:"at"`
}
func main(){
	dh := &Dinghook{
		url: "https://oapi.dingtalk.com/robot/send?access_token=3d167748ad27dca2ce18fbe842481431008ef93f47508c9192ea65770714f84c",
		levels: []logger.Level{logger.WarnLevel,logger.InfoLevel},
		toMobiles:[]string{"13912345678"},
		name: "video",
		jsonBodies: make(chan []byte),
		chan_Close: make(chan bool),
	}
	// dh.DirectSend("直接发送")
	level := logger.InfoLevel
	logger.SetLevel(level)
	//设置FileName
	logger.SetReportCaller(true)
	logger.SetFormatter(&logger.JSONFormatter{
		TimestampFormat:"2006-01-02 15:04:05",
	})
	//添加hook
	logger.AddHook(dh)
	logger.Info("云中太守的logrus")
}